// 1.引入模块
const Koa = require('koa'),
      router = require('koa-router')(),
      render = require('koa-art-template'),
      static = require('koa-static'),
      koaBody = require('koa-body'),
      session = require('koa-session'),
      path = require('path'),
      admin = require('./router/admin')

// 2.实例化koa
const app = new Koa();

//////////////////////////////////
// 3.配置
//////////////////////////////////
// 3.1 配置模板
render(app,{
    root:path.join(__dirname,"view"),
    extname:'.html',
    debug:process.env.NODE_ENV !== 'production'
});

// 3.2 配置静态资源
app.use(static('static'));

// 3.3 配置表单数据的请求体 koaBody
app.use(koaBody({
    multipart:true
}))

// 3.4 配置session
app.keys = ['some secret hurr'];

const CONFIG = {
    key: 'koa.sess',
    /** (string) cookie key (default is koa.sess) */
    /** (number || 'session') maxAge in ms (default is 1 days) */
    /** 'session' will result in a cookie that expires when session/browser is closed */
    /** Warning: If a session cookie is stolen, this cookie will never expire */
    // 默认有效期1天
    maxAge: 86400000,

    autoCommit: true,
    /** (boolean) automatically commit headers (default true) */
    //     能不能写
    overwrite: true,
    /** (boolean) can overwrite or not (default true) */
    //   cookie是否只有服务端可以访问
    httpOnly: true,
    /** (boolean) httpOnly or not (default true) */
    //   签名
    signed: true,
    /** (boolean) signed or not (default true) */
    //   
    rolling: false,
    /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
    //是否可以覆盖，到期前进行访问，更新到期时间
    renew: false,
    /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
    //   使用https进行访问 ，需要改成http改成false
    secure: false,
    /** (boolean) secure cookie*/
    sameSite: null,
    /** (string) session cookie sameSite options (default null, don't set it) */
};

app.use(session(CONFIG, app));
// or if you prefer all default config, just use => app.use(session(app));




// 3.5 路由配置
app.use(router.routes()).use(router.allowedMethods());

////////////////////////////////////////////////////

// 4.路由
// 中间件
app.use(async (ctx,next)=>{
    await next();
    if(ctx.status == 404 || !ctx.body){
        ctx.body='404,页面不存在';
    }
})

// 首页
router.get('/',ctx=>{
    ctx.body="Hello,world";
})

// 后台管理系统
router.use('/admin',admin)

// 5.开启服务器监听
app.listen(2021,()=>{
    console.log("服务器运行在http://localhost:2021");
})


